const { defineConfig } = require('@vue/cli-service')
const bodyParser = require('body-parser')
const Mock = require('mockjs')
const movie = require('./public/movie.json')

const data = Mock.mock({
  'list|50': [
    {
      'id|+1': 1,
      nm: '@ctitle',
      img: '@image(100x100, @color)',
      date: '@datetime()',
      star: '@cname',
    },
  ],
})
module.exports = defineConfig({
  transpileDependencies: true,
  devServer: {
    setupMiddlewares(middlewares, { app }) {
      app.use(bodyParser.json())

      app.get('/api/test', (req, res) => {
        res.send({
          code: 0,
        })
      })

      // 登陆接口
      app.post('/api/login', (req, res) => {
        const { username, password } = req.body
        res.send({
          code: 0,
          msg: 'success',
          data: { token: `${username}_token` },
        })
      })

      // 电影数据
      app.get('/api/list', (req, res) => {
        const { page = 1, size = 10 } = req.query
        res.send({
          code: 0,
          msg: 'success',
          data: {
            total: data.list.length,
            list: data.list.slice((page - 1) * size, page * size),
          },
        })
      })

      // 添加数据接口
      app.post('/api/add', (req, res) => {
        const listItem = req.body
        data.list.push({
          ...listItem,
          id: Date.now(),
        })
        res.send({
          code: 0,
          success: '添加成功',
          data: data.list.length,
        })
      })

      // 编辑接口
      app.post('/api/edit', (req, res) => {
        const editItem = req.body
        // 查找下标
        const editIndex = data.list.findIndex((v) => v.id === editItem.id)
        // 替换数据
        data.list.splice(editIndex, 1, editItem)
        res.send({
          code: 0,
          success: '编辑成功',
          data: data.list.length,
        })
      })
      // 删除接口
      app.get('/api/delete', (req, res) => {
        const { id } = req.query
        const deleteIndex = data.list.findIndex((v) => v.id == id)

        data.list.splice(deleteIndex, 1)
        res.send({
          code: 0,
          success: '删除成功',
          data: data.list.length,
        })
      })

      app.get('/api/detail', (req, res) => {
        const { detailId } = req.query
        res.send({
          code: 0,
          msg: 'success',
          data: movie.coming.find((v) => v.id == detailId),
        })
      })

      return middlewares
    },
  },
})
